<?

if( isset($_POST['cn']) )
    $name = $_POST['cn'];
if( isset($_POST['uid']) )
    $uid = $_POST['uid'];

if ((isset($_POST['password']) AND isset($_POST['password2'])) AND $_POST['password']) {
	if ($_POST['password'] == $_POST['password2']) {
		$pw = $_POST['password'];

                //byter lösen med smbldap-usermod
                $descriptorspec = array(
                   0 => array("pipe", "r"),  // stdin
                   1 => array("pipe", "w"),  // stdout
                   2 => array("pipe", "w")   // stderr
                );
                $process = proc_open('exec /usr/sbin/smbldap-usermod -PUJ '.escapeshellarg($name), $descriptorspec, $pipes, "/");
                fwrite($pipes[0], $pw . "\n");
                fwrite($pipes[0], $pw . "\n");
                $stout_str = stream_get_contents($pipes[1]);
                $sterr_str = stream_get_contents($pipes[2]);
                fclose($pipes[0]);
                fclose($pipes[1]);
                fclose($pipes[2]);
                $exitCode = proc_close($process);
                if( $exitCode !== 0 && strlen($sterr_str) !== 0 ) {
                        //echo "FAIL: $stout_str\n$sterr_str\n";
                        error('unknown');
                }
	} else {
		error('password_diff');
	};
};

if ($_POST['displayName']) {
	$desc = utf8_encode(unhtmlspecialchars($_POST['displayName']));
	$change["displayName"] = $desc;
	$change["gecos"] = $name;
	$dn = "uid=$name,ou=Users,".$GLOBALS["dc"];
	ldap_mod_replace($conn,$dn,$change);
};

if (isset($_POST['addToGroup']) AND ($_POST['addToGroup']!="")) {
		$group = $_POST['addToGroup'];
		$info = ldap_get_entries($conn, ldap_search($conn, $GLOBALS["dc"], "(cn=$name)"));

		$username = $info[0]['cn'][0];
		$dn = "cn=".$group.",ou=Groups,".$GLOBALS["dc"];
		
		$add['memberuid'] = $username;

		ldap_mod_add($conn,$dn,$add);
};

if (isset($_GET['delGroup']) AND $_GET['delGroup']) {
	$dn = "cn=".$_GET['delGroup'].",ou=Groups,".$GLOBALS["dc"];
	$name = $_GET['name'];
	$delete["memberuid"] = $name;
	ldap_mod_del($conn,$dn,$delete);
};
?>
